<template>
    <el-dialog v-model="DialogShow" width="30%" title="添加作业" center custom-class="custom_class ">
        <div class="main">
            <el-form :model="form" ref="ruleFormRef" label-width="auto" style="max-width: 600px" :rules="ruleForm">
                <el-form-item label="截至时间" prop="deadlineTime">
                    <el-date-picker v-model="form.deadlineTime" type="datetime" placeholder="请选择" clearable
                        format="YYYY/MM/DD hh:mm:ss" value-format="x" />
                </el-form-item>
                <el-form-item label="作业名称" prop="workName">
                    <el-input v-model="form.workName" placeholder="请输入作业名称" />
                </el-form-item>
                <el-form-item label="是否随机导入" prop="selectedOptionsNum">
                    <el-switch v-model="form.isImport" active-text="随机" inactive-text="手动" />
                </el-form-item>
                <el-form-item label="选择题库" prop="questionBankId">
                    <el-tag closable type="primary" @close="closeQuestionBankId"
                        v-if="_questionBankId.questionBankName">
                        {{ _questionBankId.questionBankName }}
                    </el-tag>
                    <div class="add" @click="questionBankShow = true" v-if="!form.questionBankId">
                        <el-icon size="50" color="#dcdfe6">
                            <Plus />
                        </el-icon>
                    </div>
                </el-form-item>
                <el-form-item label="单选题生成数量" prop="selectedOptionsNum" v-if="form.isImport">
                    <el-input-number v-model="form.selectedOptionNum" :min="1" />
                </el-form-item>
                <el-form-item label="多选题生成数量" prop="selectedOptionsNum" v-if="form.isImport">
                    <el-input-number v-model="form.selectedOptionsNum" :min="1" />
                </el-form-item>
                <el-form-item label="判断题生成数量" prop="selectedOptionsNum" v-if="form.isImport">
                    <el-input-number v-model="form.correctNum" :min="1" />
                </el-form-item>
                <el-form-item label="添加单选题目" v-if="!form.isImport" prop="selectedOptionList">
                    <div style="display: flex;align-items: flex-start;flex-wrap: wrap;padding:5px;">
                        <template v-if="form.selectedOptionList.length > 0">
                            <el-tag closable type="primary" @close="closeOptionList(0, index)"
                                v-for="item, index in form.selectedOptionList" :key="item.id"
                                style="margin: 5px;max-width: 400px;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">
                                {{ item.option }}
                            </el-tag>
                        </template>
                        <div class="add" @click="chooseType(0)">
                            <el-icon size="50" color="#dcdfe6">
                                <Plus />
                            </el-icon>
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="添加多选题目" v-if="!form.isImport" prop="selectedOptionsList">
                    <div style="display: flex;align-items: flex-start;flex-wrap: wrap;padding:5px;">
                        <template v-if="form.selectedOptionsList.length > 0">
                            <el-tag closable type="primary" @close="closeOptionList(1, index)"
                                v-for="item, index in form.selectedOptionsList" :key="item.id"
                                style="margin: 5px;max-width: 400px;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">
                                {{ item.option }}
                            </el-tag>
                        </template>
                        <div class="add" @click="chooseType(1)">
                            <el-icon size="50" color="#dcdfe6">
                                <Plus />
                            </el-icon>
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="添加判断题目" v-if="!form.isImport" prop="correctList">
                    <div style="display: flex;align-items: flex-start;flex-wrap: wrap;padding:5px;">
                        <template v-if="form.correctList.length > 0">
                            <el-tag closable type="primary" @close="closeOptionList(2, index)"
                                v-for="item, index in form.correctList" :key="item.id"
                                style="margin: 5px;max-width: 400px;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">
                                {{ item.option }}
                            </el-tag>
                        </template>
                        <div class="add" @click="chooseType(2)">
                            <el-icon size="50" color="#dcdfe6">
                                <Plus />
                            </el-icon>
                        </div>
                    </div>
                </el-form-item>
            </el-form>
        </div>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="DialogShow = false">取消</el-button>
                <el-button type="primary" @click="submitForm"> 确定 </el-button>
            </span>
        </template>
        <el-drawer v-model="drawer" size="40%" :with-header="false">
            <el-checkbox-group v-model="checkList">
                <div class="question_item">
                    <el-form :inline="true" :model="formInline" class="demo-form-inline">
                        <el-form-item label="题目名称">
                            <el-input v-model="formInline.questionContent" placeholder="请输入题目名称" clearable />
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="queryBankInfo">搜索</el-button>
                        </el-form-item>
                    </el-form>
                    <el-collapse>
                        <el-collapse-item :name="item.id" v-for="item in BankList" :key="item.id">
                            <template #title>
                                <el-checkbox @click.stop.native="() => { }"
                                    :value="item.id + ',' + item.questionContent">题目：{{ item.questionContent
                                    }}</el-checkbox>
                            </template>
                            <div class="determine_item" v-for="item in item.optionsInfoDtos" :key="item.options">
                                <span class="determine_item_option">{{ item.options }}.</span>
                                <span class="determine_item_content">{{ item.optionsContent }}</span>
                            </div>
                        </el-collapse-item>
                    </el-collapse>
                </div>
            </el-checkbox-group>
            <template #footer>
                <el-button @click="drawer = false">取消</el-button>
                <el-button type="primary" @click="confirmQuestionId">确定</el-button>
            </template>

        </el-drawer>
        <el-drawer v-model="questionBankShow" size="40%" :with-header="false">
            <el-table ref="singleTableRef" :data="CourseTableData" style="width: 100%" v-loading="loading">
                <el-table-column property="roleType" label="" align="center" width="80">
                    <template #default="{ row }">
                        <el-radio :value="row.id + ',' + row.questionBankName" v-model="_questionBankId.id"></el-radio>
                    </template>
                </el-table-column>
                <el-table-column property="id" label="ID" align="center" width="80" />
                <el-table-column property="questionBankName" label="题库名字" align="center" />
                <el-table-column property="operatorName" label="创建者" align="center" width="120" />
            </el-table>
            <div class="page" v-if="questionBankShow">
                <Pagination @getDate="getAllCourseInfo" :queryNum="queryCount" />
            </div>
            <template #footer>
                <el-button @click="questionBankShow = false">取消</el-button>
                <el-button type="primary" @click="confirmQuestionBankId">确定</el-button>
            </template>

        </el-drawer>
    </el-dialog>
</template>

<script setup>
import { reactive, ref, watch } from 'vue';

import useUserInfo from "store/useUserInfo.js";
const useUserInfoStore = useUserInfo();
import { storeToRefs } from 'pinia'
const { userInfo } = storeToRefs(useUserInfoStore)

import { getQuestionBankListApi, addHomeworkApi, getQuestionListApi } from "@/api/index";
import { ElMessage } from "element-plus";
import Pagination from "@/components/base/MyPagination.vue";

const props = defineProps(['show', 'courseId'])
const emit = defineEmits(['update:show', 'onSubmit'])
//弹窗
const DialogShow = ref(false)
// 选择作业弹窗
const drawer = ref(false)
// 选择题库弹窗
const questionBankShow = ref(false)
watch(() => props.show, (newVal) => {
    if (!newVal) {
        // 初始化表单
        drawer.value = false
        form.deadlineTime = ''
        form.workName = null
        form.selectedOptionNum = 1
        form.isImport = false
        form.selectedOptionsNum = 1
        form.correctNum = 1
        form.questionBankId = null
        form.selectedOptionList = []
        form.selectedOptionsList = []
        form.correctList = []
    }
    DialogShow.value = newVal;
});
watch(() => DialogShow.value, (newVal) => {
    emit('update:show', newVal);
});
watch(() => questionBankShow.value, (newVal) => {
    _questionBankId.value.id = null
});
// 数据收集
const form = reactive({
    deadlineTime: '',
    workName: null,
    selectedOptionNum: 1,
    isImport: false,
    selectedOptionsNum: 1,
    correctNum: 1,
    questionBankId: null,
    selectedOptionList: [],
    selectedOptionsList: [],
    correctList: []
})

// 选题类型  0单选 1多选 2判断
const type = ref(null)
// 题目列表
const BankList = ref([])
// 选择的题目
const checkList = ref([])
// 打开选题
const chooseType = (val) => {
    if (!form.questionBankId) {
        ElMessage({
            showClose: true,
            message: '请先选择题库',
            type: "error",
        });
        return
    }
    type.value = val
    // 还原选中的
    if (type.value == 0) {
        form.selectedOptionList.forEach(item => {
            checkList.value.push(item.id + "," + item.option)
        });
    } else if (type.value == 1) {
        form.selectedOptionsList.forEach(item => {
            checkList.value.push(item.id + "," + item.option)
        });
    } else if (type.value == 2) {
        form.correctList.forEach(item => {
            checkList.value.push(item.id + "," + item.option)
        });
    }
    console.log("🚀 ~ chooseType ~ checkList:", checkList.value)
    drawer.value = true
    queryBankInfo()
}
const formInline = reactive({
    questionContent: null,
})
// 查询题目
const queryBankInfo = async () => {
    // checkList.value = []
    const params = {
        pageNum: 1,
        pageSize: 1000,
        questionBankId: form.questionBankId,
        type: type.value
    }
    if (formInline.questionContent) {
        params.questionContent = formInline.questionContent
    }

    const res = await getQuestionListApi(params)
    loading.value = false;
    if (res.code !== "10000") {
        ElMessage({
            showClose: true,
            message: res.message,
            type: "error",
        });
        return;
    }
    ElMessage({
        showClose: true,
        message: `查询成功!`,
        type: "success",
    });
    BankList.value = res.data.list || [];
}
// 确认选中题目
const confirmQuestionId = () => {
    if (checkList.value.length === 0) {
        ElMessage({
            showClose: true,
            message: '请选择题目',
            type: "error",
        });
        return
    }
    drawer.value = false
    if (type.value == 0) {
        form.selectedOptionList = []
        checkList.value.forEach((item) => {
            form.selectedOptionList.push({
                id: item.split(',')[0],
                option: item.split(',')[1]
            })
        })
    } else if (type.value == 1) {
        form.selectedOptionsList = []
        checkList.value.forEach((item) => {
            form.selectedOptionsList.push({
                id: item.split(',')[0],
                option: item.split(',')[1]
            })
        })
    } else if (type.value == 2) {
        form.correctList = []
        checkList.value.forEach((item) => {
            form.correctList.push({
                id: item.split(',')[0],
                option: item.split(',')[1]
            })
        })
    }
    console.log(checkList.value);

    checkList.value = []
}
// 删除选中的某个题目
const closeOptionList = (type, index) => {
    if (type == 0) {
        form.selectedOptionList.splice(index, 1)
    } else if (type == 1) {
        form.selectedOptionsList.splice(index, 1)
    } else if (type == 2) {
        form.correctList.splice(index, 1)
    }
}

// 表单验证
const ruleForm = reactive({
    questionBankId: [
        { required: true, message: '请选择题库', trigger: 'change' },
    ],
    deadlineTime: [
        { required: true, message: '请选择截至时间', trigger: 'blur' },
    ],
    workName: [
        { required: true, message: '请输入作业名称', trigger: 'blur' },
        { min: 4, message: '名称在五个字以上', trigger: 'blur' },
    ],
    selectedOptionsNum: [
        {
            required: true,
            message: '题库封面必填',
            trigger: 'blur',
        },
    ],
    selectedOptionList: [
        {
            type: 'array',
            required: true,
            message: '请选择单选题',
            trigger: 'blur',
        },
    ],
    selectedOptionsList: [
        {
            type: 'array',
            required: true,
            message: '请选择多选题',
            trigger: 'blur',
        },
    ],
    correctList: [
        {
            type: 'array',
            required: true,
            message: '请选择判断题',
            trigger: 'blur',
        },
    ],
})

// 题库
const CourseTableData = ref([])
const queryCount = ref(1)
const loading = ref(false)
const _questionBankId = ref({
    id: null,
    questionBankName: null,
})
// 获取题库
const getAllCourseInfo = async (page) => {
    loading.value = true
    const params = {
        pageNum: page.pageNum,
        pageSize: page.pageSize,
        operatorId: userInfo.value.userId
    }
    const res = await getQuestionBankListApi(params)
    loading.value = false;
    if (res.code !== "10000") {
        ElMessage({
            showClose: true,
            message: res.message,
            type: "error",
        });
        return;
    }
    ElMessage({
        showClose: true,
        message: `查询成功!`,
        type: "success",
    });
    CourseTableData.value = res.data.list || [];
    page.totalCount = res.data.totalCount;
}
// 确认选中题库
const confirmQuestionBankId = () => {
    if (_questionBankId.value == null || _questionBankId.value == '') {
        ElMessage({
            showClose: true,
            message: '请选择题库',
            type: "error",
        });
        return
    }
    // 字符串转数组
    const questionBankId = _questionBankId.value.id.split(',')
    form.questionBankId = questionBankId[0]
    _questionBankId.value.questionBankName = questionBankId[1]
    questionBankShow.value = false
}
// 删除这次选中的题库
const closeQuestionBankId = () => {
    form.questionBankId = null
    _questionBankId.value.id = null
    _questionBankId.value.questionBankName = null
}

const ruleFormRef = ref(null);
const submitForm = async () => {
    await ruleFormRef.value.validate(async (valid, fields) => {
        if (valid) {
            const params = {
                deadlineTime: form.deadlineTime,
                workName: form.workName,
                operatorId: userInfo.value.userId,
                courseId: props.courseId,
                type: 0,
                questionBankId: form.questionBankId,
            }
            if (form.isImport) {
                params.selectedOptionType = true;
                params.selectedOptionsType = true;
                params.correctType = true;
                params.selectedOptionNum = form.selectedOptionNum;
                params.selectedOptionsNum = form.selectedOptionsNum;
                params.correctNum = form.correctNum;
            } else {
                params.selectedOptionType = false;
                params.selectedOptionsType = false;
                params.correctType = false;
                params.selectedOptionList = form.selectedOptionList.map(item => item.id);
                params.selectedOptionsList = form.selectedOptionsList.map(item => item.id);
                params.correctList = form.correctList.map(item => item.id);
            }
            const res = await addHomeworkApi(params)
            if (res.code !== "10000") {
                ElMessage({
                    showClose: true,
                    message: res.message,
                    type: "error",
                });
                return;
            }
            ElMessage({
                showClose: true,
                message: `添加成功!`,
                type: "success",
            });
            emit('onSubmit')
            _questionBankId.value.questionBankName = null
            DialogShow.value = false;
        } else {
            console.log('error submit!', fields)
        }
    })
}

</script>

<style lang="scss">
.add {
    width: 50px;
    height: 50px;
    border-radius: 4px;
    border: 1px solid #dcdfe6;
    cursor: pointer;
}

// 生效 
:deep(.el-dialog) {
    border-radius: 15px;
}

// 修改弹窗的样式
/* ::v-deep .custom_class {

} */
.determine_item {
    display: flex;
    align-items: center;
    margin: 15px 0;

    .determine_item_option {
        font-size: 14px;
        font-weight: 600;
        color: #333;
        /* margin-top: 10px; */
        height: 30px;
        line-height: 30px;
        text-align: center;

    }

    .determine_item_btn {
        display: flex;
        align-items: center;
        margin-left: 50px;
    }

    .determine_item_content {
        font-size: 14px;
        color: #333;
        /* margin-top: 10px; */
        height: 30px;
        line-height: 30px;
        text-align: center;
    }
}
</style>